package com.example.payment.controller;

import com.example.payment.dto.PaymentRequest;
import com.example.payment.dto.PaymentResponse;
import com.example.payment.entity.PaymentOrder;
import com.example.payment.enums.PaymentStatus;
import com.example.payment.service.PaymentService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/payment")
public class PaymentController {
    
    private static final Logger log = LoggerFactory.getLogger(PaymentController.class);
    
    @Autowired
    private PaymentService paymentService;
    
    /**
     * 显示支付页面
     */
    @GetMapping("/pay")
    public String showPaymentPage(@RequestParam String businessOrderNo,
                                @RequestParam String businessType,
                                @RequestParam String amount,
                                @RequestParam String description,
                                Model model,
                                HttpSession session) {
        try {
            // 从session获取用户信息
            Long userId = (Long) session.getAttribute("userId");
            String userName = (String) session.getAttribute("userName");
            
            if (userId == null) {
                return "redirect:/login";
            }
            
            model.addAttribute("businessOrderNo", businessOrderNo);
            model.addAttribute("businessType", businessType);
            model.addAttribute("amount", amount);
            model.addAttribute("description", description);
            model.addAttribute("userId", userId);
            model.addAttribute("userName", userName);
            
            return "payment/payment-form";
            
        } catch (Exception e) {
            log.error("显示支付页面失败", e);
            return "redirect:/error";
        }
    }
    
    /**
     * 创建支付订单
     */
    @PostMapping("/create")
    @ResponseBody
    public ResponseEntity<PaymentResponse> createPayment(@Valid @RequestBody PaymentRequest request,
                                                       HttpSession session) {
        try {
            // 验证用户身份
            Long sessionUserId = (Long) session.getAttribute("userId");
            if (sessionUserId == null || !sessionUserId.equals(request.getUserId())) {
                return ResponseEntity.badRequest()
                    .body(PaymentResponse.builder()
                        .success(false)
                        .errorCode("UNAUTHORIZED")
                        .errorMessage("用户未授权")
                        .build());
            }
            
            PaymentResponse response = paymentService.createPayment(request);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("创建支付订单失败", e);
            return ResponseEntity.badRequest()
                .body(PaymentResponse.builder()
                    .success(false)
                    .errorCode("CREATE_FAILED")
                    .errorMessage("创建支付订单失败: " + e.getMessage())
                    .build());
        }
    }
    
    /**
     * 查询支付状态
     */
    @GetMapping("/status/{orderNo}")
    @ResponseBody
    public ResponseEntity<PaymentResponse> queryPaymentStatus(@PathVariable String orderNo) {
        try {
            PaymentResponse response = paymentService.queryPaymentStatus(orderNo);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("查询支付状态失败", e);
            return ResponseEntity.badRequest()
                .body(PaymentResponse.builder()
                    .success(false)
                    .errorCode("QUERY_FAILED")
                    .errorMessage("查询失败: " + e.getMessage())
                    .build());
        }
    }
    
    /**
     * 支付成功页面
     */
    @GetMapping("/success")
    public String paymentSuccess(@RequestParam String orderNo, Model model) {
        try {
            PaymentResponse response = paymentService.queryPaymentStatus(orderNo);
            model.addAttribute("orderNo", orderNo);
            model.addAttribute("status", response.getStatus());
            model.addAttribute("businessOrderNo", response.getBusinessOrderNo());
            
            return "payment/payment-success";
            
        } catch (Exception e) {
            log.error("显示支付成功页面失败", e);
            return "redirect:/error";
        }
    }
    
    /**
     * 支付失败页面
     */
    @GetMapping("/failed")
    public String paymentFailed(@RequestParam String orderNo,
                              @RequestParam(required = false) String errorMessage,
                              Model model) {
        try {
            model.addAttribute("orderNo", orderNo);
            model.addAttribute("errorMessage", errorMessage);
            
            return "payment/payment-failed";
            
        } catch (Exception e) {
            log.error("显示支付失败页面失败", e);
            return "redirect:/error";
        }
    }
    
    /**
     * 用户订单列表
     */
    @GetMapping("/orders")
    public String getUserOrders(Model model, HttpSession session) {
        try {
            Long userId = (Long) session.getAttribute("userId");
            if (userId == null) {
                return "redirect:/login";
            }
            
            List<PaymentOrder> orders = paymentService.getUserOrders(userId);
            model.addAttribute("orders", orders);
            
            return "payment/order-list";
            
        } catch (Exception e) {
            log.error("获取用户订单列表失败", e);
            return "redirect:/error";
        }
    }
    
    /**
     * 支付回调处理
     */
    @PostMapping("/callback/{channel}")
    @ResponseBody
    public String handleCallback(@PathVariable String channel,
                               @RequestParam Map<String, String> params,
                               HttpServletRequest request) {
        try {
            log.info("收到支付回调: channel={}, params={}", channel, params);
            
            // 添加客户端IP
            params.put("clientIp", getClientIp(request));
            
            boolean success = paymentService.handleCallback(params);
            
            if (success) {
                return "SUCCESS";
            } else {
                return "FAIL";
            }
            
        } catch (Exception e) {
            log.error("处理支付回调失败", e);
            return "FAIL";
        }
    }
    
    /**
     * 获取客户端IP
     */
    private String getClientIp(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty() && !"unknown".equalsIgnoreCase(xForwardedFor)) {
            return xForwardedFor.split(",")[0];
        }
        
        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty() && !"unknown".equalsIgnoreCase(xRealIp)) {
            return xRealIp;
        }
        
        return request.getRemoteAddr();
    }
} 